package com.fantuan.db.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.fantuan.db.bean.ConsumeLog;

@Service
public class ConsumeLogDAO extends BaseDAO{

	/**
	 * 获取饭团的某一比消费
	 * @param nid
	 * @return
	 * @throws SQLException
	 */
	public ConsumeLog getConsumeLog(int nid) throws SQLException {

		Connection conn = dataSource.getConnection();

		String sql = "select * from t_yw_ftconsumelog where nid=?";

		ConsumeLog result = null;
		try {

			Object[] objs = new Object[] { nid };

			result = (ConsumeLog) this.query(conn, sql, new BeanHandler<ConsumeLog>(
					ConsumeLog.class), objs);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.close(conn);
		}

		return result;
	}
	
	
	
	public void removeConsumeLog(int nid) throws SQLException {

		Connection conn = dataSource.getConnection();

		String sql = "delete from t_yw_ftconsumelog where nid=?";

		try {

			Object[] objs = new Object[] { nid };

			this.update(conn, sql, objs);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.close(conn);
		}
	}
	
	
	
	
	public long addConsumeLog(ConsumeLog consumeLog) throws SQLException {

		Connection conn = dataSource.getConnection();

		String sql = "insert into t_yw_ftconsumelog(nGroupID,nConsumeUserID,sRemark,nAllMoney,dConsumeDate,dUpdateTime,sAddress,nConsumerCount) values(?,?,?,?,?,now(),?,?)";

		long result = -1;
		try {

			Object[] objs = new Object[] { 
					consumeLog.getnGroupID(),
					consumeLog.getnUserID(),
					StringUtils.trimToEmpty(consumeLog.getsRemark()),
					consumeLog.getnMoney(),
					consumeLog.getdConsumeDate(),
					consumeLog.getsAddress(),
					consumeLog.getnConsumerCount()};

			this.update(conn, sql, objs);
			result = this.getLastInsertID(conn);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.close(conn);
		}

		return result;
	}
	
	
	
	/**
	 * 获取某用户付款的某一比消费，倒序输出
	 * @param consumeUserID
	 * @return
	 * @throws SQLException
	 */
	public List<ConsumeLog> getConsumeLogByConsumeUserID(int consumeUserID) throws SQLException {

		Connection conn = dataSource.getConnection();

		String sql = "select * from t_yw_ftconsumelog where nConsumeUserID=? order by nID desc";

		List<ConsumeLog> result = null;
		try {

			Object[] objs = new Object[] { consumeUserID };

			result = (List<ConsumeLog>) this.query(conn, sql, new BeanListHandler<ConsumeLog>(
					ConsumeLog.class), objs);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.close(conn);
		}

		return result;
	}

}
